package com.cuit.qx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cuit.qx.aop.OperLog;
import com.cuit.qx.bean.Threshold;
import com.cuit.qx.bean.User;
import com.cuit.qx.bean.WeatherStation;
import com.cuit.qx.service.AddWeatherStationService;
import com.cuit.qx.service.WeatherStationService;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.thymeleaf.util.ListUtils.isEmpty;


/**
 * @Author:wjd
 * @Description: 站点管理
 * @date:Created in 17:07 2020/9/17
 * @Modified By:
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/sites")
public class WeatherStationController {

    @Autowired
    WeatherStationService stationService;

    @RequestMapping("/getAllSites")
    @OperLog(operModul = "站点管理", operType = "1", operDesc = "查询站点信息")
    public ReturnData getAllLog(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        List<WeatherStation> allWeatherStation = stationService.getAllWeatherStation(pageNo, pageSize);

        if (!isEmpty(allWeatherStation)) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), allWeatherStation);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }

    @RequestMapping("/getSitesList")
    @OperLog(operModul = "站点管理", operType = "1", operDesc = "查询全部站点信息")
    public ReturnData getAllSites() {

        List<Map<String, Object>> allWeatherStation = stationService.getMapSiteAll();

        if (!isEmpty(allWeatherStation)) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), allWeatherStation.size(), allWeatherStation);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }


    @RequestMapping("/getCounty")
    public ReturnData getCounty() {
        List<String> list = stationService.getCounty();
        if (!isEmpty(list)) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), list.size(), list);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }

    }


    /**
     * @return
     * @Author:wjd on 2020/9/16 17:45
     * @param:
     * @Description: 站点模板下载
     */
    @RequestMapping(value = "/exportXlsTemplate")
    @OperLog(operModul = "站点管理", operType = "6", operDesc = "站点模板下载")
    public ModelAndView exportXlsTemplate(HttpServletResponse res, HttpServletRequest req) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<WeatherStation> sysUsers = new ArrayList<WeatherStation>();
        WeatherStation c = new WeatherStation();
        sysUsers.add(c);
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "站点模板");
        mv.addObject(NormalExcelConstants.CLASS, WeatherStation.class);
        ExportParams exportParams = new ExportParams("导入站点模板", "导出人:" + user.getUsername(), "站点管理");
        exportParams.setImageBasePath("");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, sysUsers);
        return mv;
    }

    /**
     * @return
     * @Author:wjd on 2020/9/16 18:16
     * @param:
     * @Description: 导入站点表
     */
    @RequestMapping(value = "/importExcel")
    @OperLog(operModul = "站点管理", operType = "5", operDesc = "导入站点数据")
    public ReturnData importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                int count = 0;
                List<WeatherStation> listSysAnnouncements = ExcelImportUtil.importExcel(file.getInputStream(), WeatherStation.class, params);
                List<WeatherStation> collect = listSysAnnouncements.stream().filter(item ->
                        judgeNumber(item.getLatitude().toString()) &&
                                judgeNumber(item.getLongitude().toString())
                ).collect(Collectors.toList());
                for (WeatherStation sysAnnouncementExcel : collect) {
                    if (sysAnnouncementExcel.getStationNumber() != null && sysAnnouncementExcel.getStationName() != null
                            && sysAnnouncementExcel.getLongitude() != null && sysAnnouncementExcel.getLatitude() != null) {
                        QueryWrapper<WeatherStation> queryWrapper = new QueryWrapper();
                        queryWrapper.eq("station_number", sysAnnouncementExcel.getStationNumber());
                        WeatherStation one = stationService.getOne(queryWrapper);
                        if (one == null) {
                            // 默认设置状态为启用
                            sysAnnouncementExcel.setState("1");
                            if (sysAnnouncementExcel.getStationType() == null) {
                                sysAnnouncementExcel.setStationType("0");
                            }
                            stationService.save(sysAnnouncementExcel);
                        } else {
                            count++;
                        }
                    } else {
                        count++;
                    }
                }
                if (count == 0) {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "文件导入成功！导入数据行数：" + collect.size() + "不符合条件数据" + (listSysAnnouncements.size() - collect.size() + "行"));
                } else {
                    return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "文件导入成功！导入数据行数：" + (collect.size() - count) + "！不符合条件行数：" + (listSysAnnouncements.size() - collect.size() + count));
                }
//                return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "文件导入成功！数据行数：" + count);
            } catch (Exception e) {
//                log.error(e.getMessage(),e);
                return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件导入失败:原因" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ReturnData(ReturnStateCode.FAILED.getCode(), "文件导入失败！");
    }


    /**
     * 新增站点信息
     *
     * @param weatherStation 站点对象
     * @return
     */
    @RequestMapping(value = "/addWeather", method = RequestMethod.POST)
    @OperLog(operModul = "站点管理", operType = "2", operDesc = "新增站点信息")
    @ResponseBody
    public ReturnData addWeather(@RequestBody WeatherStation weatherStation) {
        int num = stationService.insertWeather(weatherStation);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), weatherStation);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }


    /**
     * 根据站号、站名、区县模糊查询和站点类型查询
     *
     * @param pageNo        当前页数
     * @param pageSize      每页条数
     * @param stationNumber 站号
     * @param stationName   站名
     * @param stationCounty 区县
     * @param stationType   站点类型
     * @return
     */
    @RequestMapping(value = "/getWeather", method = RequestMethod.GET)
    @OperLog(operModul = "站点管理", operType = "1", operDesc = "根据站号模糊查询")
    @ResponseBody
    public ReturnData getWeather(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 String stationNumber, String stationName, String stationCounty, String stationType) {
        if (pageNo > 0) {
            List<WeatherStation> weatherStations = stationService.getWeather(pageNo, pageSize, stationNumber, stationName, stationCounty, stationType);
            int num = stationService.getFoggyWeatherNum(stationNumber, stationName, stationCounty, stationType);
            if (!isEmpty(weatherStations)) {
                return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), num, weatherStations);
            } else {
                return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
            }
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }


    /**
     * 根据id单条修改站点信息
     *
     * @param weatherStation 站点对象
     * @return
     */
    @RequestMapping(value = "/updateWeather", method = RequestMethod.POST)
    @OperLog(operModul = "站点管理", operType = "3", operDesc = "根据id单条修改站点信息")
    @ResponseBody
    public ReturnData updateWeather(@RequestBody WeatherStation weatherStation) {
        int num = stationService.updateWeather(weatherStation);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    /**
     * 根据id批量修改站点信息
     *
     * @param weatherStations 多个站点对象
     * @return
     */
    @RequestMapping(value = "/updateWeatherList", method = RequestMethod.POST)
    @OperLog(operModul = "站点管理", operType = "3", operDesc = "根据id批量修改站点信息")
    @ResponseBody
    public ReturnData updateWeatherList(@RequestBody List<WeatherStation> weatherStations) {
        int num = stationService.updateWeatherList(weatherStations);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }


    /**
     * 根据多个站号查询对应站点信息
     *
     * @param stationNumberData 站号
     * @return
     */
    @RequestMapping(value = "/getWeatherBySitesNumber", method = RequestMethod.POST)
    @OperLog(operModul = "站点管理", operType = "1", operDesc = "根据多个站号查询对应站点信息")
    @ResponseBody
    public ReturnData getWeatherByStationNumber(@RequestBody Map<String, List<String>> stationNumberData) {
        List<String> stationNumbers = stationNumberData.get("stationNumbers");
        List<WeatherStation> weatherStation = stationService.getWeatherByStationNumber(stationNumbers);
        if (weatherStation != null) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), weatherStation);
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.SUCCEEBUT.getMsg());
        }
    }

    /**
     * 根据站点id删除站点信息
     *
     * @param id 站点id
     * @return
     */
    @RequestMapping(value = "/deleteWeatherById", method = RequestMethod.GET)
    @OperLog(operModul = "站点管理", operType = "4", operDesc = "根据站点id删除站点信息")
    @ResponseBody
    public ReturnData deleteWeatherById(String id) {
        int num = stationService.deleteWeatherById(id);
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    /**
     * 批量删除站点id删除站点信息
     *
     * @param map 站点ids
     * @return
     */
    @RequestMapping(value = "/deleteWeatherByIds", method = RequestMethod.POST)
    @OperLog(operModul = "站点管理", operType = "4", operDesc = "根据站点id删除站点信息")
    @ResponseBody
    public ReturnData deleteWeatherByIds(@RequestBody Map<String, String> map) {
        String ids = map.get("ids");
        int num = stationService.deleteWeatherByIds(ids.split(","));
        if (num > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    public static boolean judgeNumber(String number) {
        return Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])").matcher(number).matches();
    }

    /**
     * 查询站号是否重复, 重复返回false,不重复返回true
     *
     * @param stationNumber 站号
     * @return
     */
    @RequestMapping(value = "/boolWeatherStationNumber", method = RequestMethod.GET)
    @OperLog(operModul = "站点管理", operType = "1", operDesc = "查询站号是否重复")
    @ResponseBody
    public boolean boolWeatherStationNumber(String stationNumber) {
        int num = stationService.boolWeatherStationNumber(stationNumber);
        if (num > 0) {
            return false;
        } else {
            return true;
        }
    }
    @RequestMapping(value = "/getByNoStaionData", method = RequestMethod.GET)
    @ResponseBody
    public ReturnData getByNoStaionData(String StaionName){
        LambdaQueryWrapper<WeatherStation> wrapper=new LambdaQueryWrapper();
        wrapper.like(WeatherStation::getStationName,StaionName);
        List <WeatherStation> one = stationService.list(wrapper);
        return new ReturnData(ReturnStateCode.SUCCEE.getCode(),ReturnStateCode.SUCCEE.getMsg(),one);
    }


}
